import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Table, Modal, Button,Icon, Select, Row, Col, Input,Checkbox,Popover,message,Spin } from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;

import BillingService from 'containers/financial-management/wait-for-billing/wait-for-billing.service'
class AddressPicker extends React.Component{
  constructor(props){
    super(props);

    this.state = {
      loading:false,
      btnLoading: false,
      showForm:false,
      flag:'',
      selectedRowKeys: [],
      selectedRows:[],
      selectedData:{},
      data:[],
      provinces:[],
      editRecord:{},
      defaultContactOID:'',
      provinceCode:'',
      cityCode:'',
      areaCode:'',
      cities:[],
      areas:[],
      columns:[
        {
          title:messages('financial-management.key377'/*姓名*/),key:'fullName',dataIndex:'fullName',width:'12%'
        },
        {
          title:messages('financial-management.key378'/*详细地址*/),key:'fullReceiverAddress',dataIndex:'fullReceiverAddress',render:(record) => <Popover content={record}>{record}</Popover>
        },
        {
          title:messages('financial-management.key379'/*手机号*/),key:'phone',dataIndex:'phone',width:'14%'
        },
        {
          title:messages('financial-management.key380'/*邮编*/),key:'zipCode',dataIndex:'zipCode',width:'10%'
        },
        {
          title:messages('financial-management.key381'/*修改收货地址*/),key:'operate',dataIndex:'operate',width:'14%',render:(text,record) =>(<span onClick={(e)=>this.handleEditAddress(e,record)}><a>{messages('financial-management.key381'/*修改收货地址*/)}</a></span>)
        }
      ],
      page: 0,
      pagination: {
        current: 1,
        total: 0,
        pageSize: 5,
        onChange: this.onChangePager
      },
      rowSelection :{
        type: 'radio',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem
      },
      cityFetching:false,
      areaFetching:false
    }
  }
  componentDidMount(){
    this.setState({loading:true});
    this.getAddressList()
    this.getAllProvinces()
    this.getDefaultAddress()
  }

  //获取收货地址列表
  getAddressList(){
    let {pagination,page,pageSize} = this.state;
    let params = {}
    params.page = page;
    params.size =pagination.pageSize;
    this.setState({loading:true})
    BillingService.getAddresses(this.props.company.companyOID,params).then(res =>{
      if(res.status === 200){
        pagination.total = Number(res.headers['x-total-count']);
        pagination.current = page+1;
        this.setState({loading:false,data:res.data,pagination})
      }
    })
  }

  //翻页
  onChangePager = pageNum =>{
    let {page} = this.state;
    if(pageNum -1 !== page){
      this.setState({
        page:pageNum-1
      },()=>{
        this.getAddressList()
      })
    }
  }

  //获得默认地址
  getDefaultAddress(){
    let {rowSelection} = this.state;
    if(this.props.flag === 'new'){
      BillingService.getDefaultAddress().then(res =>{
        rowSelection.selectedRowKeys = [res.data.billingContactOID];
        this.setState({defaultContactOID:res.data.billingContactOID,rowSelection})
      })
    }else{
      rowSelection.selectedRowKeys = [this.props.billingContactOID];
      this.setState({defaultContactOID:this.props.billingContactOID,rowSelection})
    /*  BillingService.getBillContactDetail(this.props.billingContactOID).then(res =>{
        rowSelection.selectedRowKeys = [res.data.billingContactOID];
        this.setState({defaultContactOID:res.data.billingContactOID,rowSelection})
      })*/
    }
  }

  handleEditAddress = (e,record)=>{
    this.props.form.setFieldsValue({isDefault:record.isDefault});
    this.setState({editRecord:record,showForm:true,flag:'edit'})
  }

  onSelectChange = (selectedRowKeys, selectedRows) =>{
    let {rowSelection} = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    // rowSelection.selectedRows = selectedRows;
    this.setState({rowSelection})
  }

  onSelectItem = (record, selected, selectedRows) => {
    this.setState({selectedData:record})
  };

  getAllProvinces(){
    BillingService.getAllProvinces().then(res =>{
      this.setState({provinces:res.data})
    })
  }

  handleProvinceChange = (value)=>{
    const {setFieldsValue}  = this.props.form;
    const {provinces} = this.state;
    setFieldsValue({cityRegion:'',area:''})
    let provinceName = provinces.filter(item =>item.code ===value)[0].name
    this.setState({provinceCode:provinceName,cities:[],areas:[]},()=>{
      this.getCities(value)
    })
  }

  handleCityChange = (value)=>{
    const {setFieldsValue}  = this.props.form;
    let{cities,provinceCode} = this.state
    setFieldsValue({area:''})
    let CityName = cities.filter(item =>item.code ===value)[0].name
    this.setState({cityCode:CityName},()=>{
      let params = {}
      params.provinceName = provinceCode
      params.cityName = cities.filter(item => item.code ===value)[0].name
      this.getAreas(params)
    })
  }

  handleAreaChange = (value)=>{
    const {areas} = this.state;
    let AreaName = areas.filter(item =>item.code ===value)[0].name
    this.setState({areaCode:AreaName})
  }

  getCities(code){
    this.setState({cityFetching:true})
    BillingService.getCities(code).then(res =>{
      this.setState({cities:res.data,cityFetching:false})
    })
  }

  getAreas(params){
    this.setState({areaFetching:true})
    BillingService.getAreas(params).then(res =>{
      this.setState({areas:res.data,areaFetching:false})
    })
  }

  handleShowForm = ()=>{
    this.setState({showForm:true,editRecord:{},flag:'new'})
  }

  handleHideForm = ()=>{
    this.setState({showForm:false})
  }

  //保存收货地址
  handleSaveAddress = (e)=>{
    e.preventDefault();
    let {editRecord,flag,provinceCode,cityCode,areaCode} = this.state;
    this.props.form.validateFieldsAndScroll((err,values) =>{
      if(!err){
        values.billingContactOID = flag === 'edit' ? editRecord.billingContactOID : null;
        values.companyOID = editRecord.companyOID;
        values.country = "中国";
        values.deleted = editRecord.deleted;
        values.checked = editRecord.checked;
        values.stateProvince = provinceCode ? provinceCode : editRecord.stateProvince;
        values.cityRegion = cityCode ? cityCode : editRecord.cityRegion;
        values.area && (values.area = areaCode ? areaCode : editRecord.area);
        values.streetLine = values.streetLine.trim();
        delete values.stateCountry;
        this.editAddress(flag,values);
      }
    })
  }

  //编辑&新增收货地址
  editAddress = (flag,params) =>{
    this.setState({btnLoading: true});
    BillingService.editAddress(flag,params).then(res =>{
      flag === 'edit' ? message.success(messages('financial-management.key382'/*修改成功*/)) : message.success(messages('financial-management.key383'/*新增成功*/));
      this.setState({editRecord:{}});
      this.getAddressList();
      this.getDefaultAddress();
      this.setState({showForm: false, btnLoading: false});
    })
  }

  handleOk = ()=>{
    let {selectedData} = this.state;
    this.props.onCancel();
    if(Object.keys(selectedData).length ===0 ) return
    this.props.moreAdress(selectedData)
  }

  render(){
    const {visible,onCancel} = this.props;
    const {data,columns,loading,rowSelection,provinces,cities,areas,showForm,editRecord,pagination,cityFetching,areaFetching,btnLoading} = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 14, offset: 1}
    };
    return (
      <div>
        <Modal visible={visible} width={800} onCancel={onCancel} title={messages('financial-management.key384'/*收货地址*/)} onOk={this.handleOk}>
        <Table dataSource={data}
               columns={columns}
               loading={loading}
               rowSelection={rowSelection}
               pagination={pagination}
               bordered
               size='middle'
               rowKey='billingContactOID'
        />
        <Button type='primary' onClick={this.handleShowForm}>{messages('financial-management.key385'/*新增地址*/)}<Icon type="plus-circle-o" /></Button>
          {showForm && <Form onSubmit={this.handleSaveAddress}>
            <Row gutter={30}>
              <Col span={6}>
                <div  style={{position:'relative'}}>
                  <FormItem label={messages('financial-management.key386'/*所在地区*/)}>
                    {getFieldDecorator("stateCountry",{
                      initialValue:"中国"
                    })(
                      <Input disabled/>
                    )}
                  </FormItem>
                </div>
              </Col>
              <Col span={6}>
                <div id='selectProvince' style={{position:'relative'}}>
                <FormItem label={messages('financial-management.key387'/*请选择省份*/)}>
                  {getFieldDecorator("stateProvince",{
                    rules:[
                      {
                        required:true,
                        message:messages('financial-management.key387'/*请选择省份*/)
                      }
                    ],
                    initialValue:editRecord ? editRecord.stateProvince :''
                  })(
                    <Select onChange={this.handleProvinceChange}
                            placeholder={messages('financial-management.key387'/*请选择省份*/)}
                            getPopupContainer={()=>document.getElementById('selectProvince')}>
                      {provinces.map(item=><Option key={item.code}>{item.name}</Option>)}
                    </Select>
                  )}
                </FormItem>
                </div>
              </Col>
              <Col span={6}>
                <div id='selectCity' style={{position:'relative'}}>
                <FormItem label={messages('financial-management.key388'/*请选择城市*/)}>
                  {getFieldDecorator("cityRegion",{
                    rules:[
                      {
                        required:true,
                        message:messages('financial-management.key388'/*请选择城市*/)
                      }
                    ],
                    initialValue:editRecord ? editRecord.cityRegion :''
                  })(
                    <Select onChange={this.handleCityChange}
                            placeholder={messages('financial-management.key388'/*请选择城市*/)}
                            getPopupContainer={()=>document.getElementById('selectCity')}
                            notFoundContent={cityFetching ? <Spin size="small" /> : messages('financial-management.key389'/*无匹配结果*/)}>
                      {cities.map(item=><Option key={item.code}>{item.name}</Option>)}
                    </Select>
                  )}
                </FormItem>
                </div>
              </Col>
              <Col span={6}>
                <div id='selectArea' style={{position:'relative'}}>
                <FormItem label={messages('financial-management.key390'/*请选择区域*/)}>
                  {getFieldDecorator("area",{
                    rules:[
                      {
                        required:false,
                        message:messages('financial-management.key390'/*请选择区域*/)
                      }
                    ],
                    initialValue:editRecord ? editRecord.area :''
                  })(
                    <Select onChange={this.handleAreaChange}
                            placeholder={messages('financial-management.key390'/*请选择区域*/)}
                            getPopupContainer={()=>document.getElementById('selectArea')}
                            notFoundContent={areaFetching ? <Spin size="small" /> : messages('financial-management.key389'/*无匹配结果*/)}>
                      {areas.map(item=><Option key={item.code}>{item.name}</Option>)}
                    </Select>
                  )}
                </FormItem>
                </div>
              </Col>
            </Row>
            <Row gutter={30}>
              <Col>
                <FormItem {...formItemLayout} label={messages('financial-management.key378'/*详细地址*/)}>
                  {getFieldDecorator("streetLine",{
                    rules:[
                      {
                        required:true,
                        message:messages('financial-management.key391'/*请输入详细地址*/)
                      }
                    ],
                    initialValue:editRecord ? editRecord.streetLine :''
                  })(
                    <Input placeholder={messages('financial-management.key391'/*请输入详细地址*/)}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={30}>
              <Col>
                <FormItem {...formItemLayout} label={messages('financial-management.key392'/*邮政编码*/)}>
                  {getFieldDecorator("zipCode",{
                    rules:[
                      {
                        required:true,
                        message:messages('financial-management.key393'/*请输入邮政编码*/)
                      },
                      {
                        pattern:/^[0-9][0-9]{5}$/,
                        message:messages('financial-management.key394'/*请输入正确的邮政编码*/)
                      }
                    ],
                    initialValue:editRecord ? editRecord.zipCode :''
                  })(
                    <Input placeholder={messages('financial-management.key393'/*请输入邮政编码*/)}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={30}>
              <Col>
                <FormItem {...formItemLayout} label={messages('financial-management.key395'/*收货人姓名*/)}>
                  {getFieldDecorator("fullName",{
                    rules:[
                      {
                        required:true,
                        message:messages('financial-management.key396'/*请输入收货人姓名*/)
                      }
                    ],
                    initialValue:editRecord ? editRecord.fullName :''
                  })(
                    <Input placeholder={messages('financial-management.key396'/*请输入收货人姓名*/)} />
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={30}>
              <Col>
                <FormItem {...formItemLayout} label={messages('financial-management.key397'/*手机号码*/)}>
                  {getFieldDecorator("phone",{
                    rules:[
                      {
                        required:true,
                        message:messages('financial-management.key398'/*请输入手机号码*/)
                      },
                      {
                        pattern: "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$",
                        message:messages('financial-management.key399'/*请输入正确的手机号码*/)
                      }
                    ],
                    initialValue:editRecord ? editRecord.phone :''
                  })(
                    <Input placeholder={messages('financial-management.key398'/*请输入手机号码*/)}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={30}>
              <Col>
                <FormItem>
                  {getFieldDecorator("isDefault",{
                    valuePropName: 'checked',
                    initialValue: editRecord ? editRecord.isDefault : false
                  })(
                    <Checkbox>{messages('financial-management.key400'/*设为默认*/)}</Checkbox>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Button onClick={this.handleHideForm}>{messages('financial-management.key401'/*取消*/)}</Button>
              <Button style={{ marginLeft: 8 }} htmlType="submit" type="primary" loading={btnLoading}>{messages('financial-management.key402'/*保存*/)}</Button>
            </Row>
          </Form>
          }
        </Modal>
      </div>
    )
  }
}
function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

AddressPicker.propTypes = {
  visible:React.PropTypes.bool,
  onCancel:React.PropTypes.func,
  moreAdress:React.PropTypes.func,
  flag:React.PropTypes.string,
  billingContactOID:React.PropTypes.string
}
const wrapperAddressPicker = Form.create()(AddressPicker)
export  default connect(mapStateToProps)(wrapperAddressPicker)
